package tech.wangpai.service;

import org.springframework.stereotype.Service;

import java.time.LocalDateTime;

@Service
public class OrderService {
    private final RedisLock redisLock;
    private static final int TIME_OUT = 10 * 1000;

    public OrderService(RedisLock redisLock) {
        this.redisLock = redisLock;
    }

    public Boolean order() {
        System.out.println("进入下单方法：" + LocalDateTime.now().toString());

        String productId = "111";
        long time = System.currentTimeMillis() + TIME_OUT;
        if (!redisLock.lock(productId, String.valueOf(time))) {
            throw new RuntimeException("哎呦喂！请稍后再试");
        }
        try {
            Thread.sleep(3000);
            System.out.println("========下单成功=======");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            redisLock.unlock(productId, String.valueOf(time));
        }
        return true;
    }
}
